package com.deprice4u;

import java.util.ArrayList;
import java.io.*;
import java.net.*;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import android.util.Log;

public class SocialSearcher { 
	private String strBasicSearchURL = "http://deprice4u.appspot.com/searcher?method=search_by_keyword&keyword=";
	
	public ArrayList<SocialData> 
	searchByKeyword(String strKeyword, int start_offset, int limit){
		String strKeywordUtf8=null;
		ArrayList<SocialData> retSocialDataList = new ArrayList<SocialData>();
		
    	try {
    		strKeywordUtf8 = URLEncoder.encode(strKeyword, "UTF8");
		} catch (UnsupportedEncodingException e1) {
			Log.e(Deprice.TAG, e1.getMessage());
			return null;
		}
    	
    	try{
    		URL queryURL = new URL(
    				strBasicSearchURL + strKeywordUtf8);

			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(queryURL.openStream());
			NodeList items = doc.getElementsByTagName("item");
			
			int totalItems = items.getLength();
			Log.i(Deprice.TAG, "totalItems: "+ totalItems);
			int i = 0;
			for(i=0; i<totalItems; ++i){
				Node item = items.item(i);
				if(item.getNodeType() == Node.ELEMENT_NODE){
					SocialData ItemData = new SocialData();
					ItemData.title = ((Element)item).getElementsByTagName("title").item(0).getChildNodes().item(0).getNodeValue().trim();
					ItemData.social_provider = ((Element)item).getElementsByTagName("social_provider").item(0).getChildNodes().item(0).getNodeValue().trim();
					
					Log.i(Deprice.TAG, "title: "+ ItemData.title);
					Log.i(Deprice.TAG, "social_provider: "+ ItemData.social_provider);
					
					/* TODO: Need to add code*/
					
					
					retSocialDataList.add(ItemData);
				}
			}
			
    	} catch(IOException ie)
    	{
    		Log.e(Deprice.TAG, ie.getMessage());
    		return null;
    	} catch(Exception e)
    	{
    		Log.e(Deprice.TAG, e.getMessage());
    		return null;
    	}
   	
		return retSocialDataList;
	}
}
